<script setup lang="ts">
import { onMounted, Ref, ref, computed } from 'vue'
import {
  Card,
  List,
  Space,
  Button,
  Input,
  Message,
  Empty,
  Divider,
  Form,
  FormItem,
  Textarea,
  Modal,
  Radio,
  Select,
  InputTag,
  Checkbox
} from '@arco-design/web-vue'
import { useUserStore, useTeamStore } from '@/store'
import { acceptInviteUsingPost, listTeamUserHistoryUsingPost } from '@/api/teamController'
import dayjs from 'dayjs'
import { addTeamUsingPost } from '@/api/teamController'
import { useRouter } from 'vue-router'
const router = useRouter()
const userStore = useUserStore()
const teamStore = useTeamStore()

// 创建团队弹窗控制
const createTeamVisible = ref(false)

// 创建团队表单
const createTeamForm = ref({
  name: '',
  description: '',
  maxMember: 5
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入团队名称' },
    { minLength: 1, message: '团队名称至少1个字符' },
    { maxLength: 32, message: '团队名称最多32个字符' }
  ],
  description: [{ maxLength: 300, message: '团队简介最多300个字符' }],
  maxMember: [{ required: true, message: '请选择团队人数上限' }]
}

// 团队可见性选项
const visibilityOptions = [
  { label: '私密团队', value: 'private' },
  { label: '公开团队', value: 'public' }
]

// 团队人数选项
const memberLimitOptions = [
  { label: '5人', value: 5 },
  { label: '10人', value: 10 },
  { label: '20人', value: 20 },
  { label: '50人', value: 50 }
]

// 邀请记录相关
interface InviteRecord {
  id: number
  teamId: number
  teamName: string
  inviterId: number
  inviterName: string
  inviteTime: string
  status: 'pending' // 目前只显示待处理的
}

const inviteRecords = ref<API.TeamUserHistoryVo[]>()

// 邀请链接相关
const inviteLink = ref('')
const inviteCode = ref('')

// 添加链接验证相关的状态
const inviteLinkValid = ref(false)

// 添加计算属性来控制输入框禁用状态
const isLinkDisabled = computed(() => !!inviteCode.value)
const isCodeDisabled = computed(() => !!inviteLink.value)

// 修改处理输入的方法
const handleLinkInput = (value: string) => {
  inviteLink.value = value
  // 如果输入了链接，清空邀请码
  if (value) {
    inviteCode.value = ''
  }
}

const handleCodeInput = (value: string) => {
  inviteCode.value = value
  // 如果输入了邀请码，清空链接
  if (value) {
    inviteLink.value = ''
  }
}

// 处理加入团队
const handleJoinTeam = async () => {
  console.log(inviteCode.value)
  if (inviteCode.value) {
    // 如果有邀请码，构造完整URL
    const baseUrl = import.meta.env.VITE_APP_LINK_URL
    const fullUrl = `${baseUrl}/link/${inviteCode.value}`
    console.log(fullUrl)
    window.open(fullUrl, '_blank')
  } else if (inviteLink.value) {
    // 如果有邀请链接，直接打开
    window.open(inviteLink.value, '_blank')
  }
  // 清空输入
  inviteLink.value = ''
  inviteCode.value = ''
}

// 处理邀请操作
const handleInvite = async (record: API.TeamUserHistoryVo, accept: boolean) => {
  try {
    // TODO: 调用接受/拒绝邀请的接口
    console.log(record)
    const res: any = await acceptInviteUsingPost({
      id: record.id,
      invitedId: record.invitedId,
      result: accept ? 1 : 0
    })
    // 刷新团队状态
    if (res.data) {
      Message.success(accept ? '已接受邀请' : '已拒绝邀请')
      await teamStore.getTeamUserVo()
    } else {
      Message.error(res.message || '操作失败')
    }
    // 重新加载邀请记录
    await loadInviteRecords()
  } catch (error) {
    Message.error('操作失败')
  }
}


const formRef = ref()
// 创建团队方法
const handleCreateTeam = async () => {
  try {
    if (!formRef.value) {
      return
    }
    const errorvalid = await formRef.value.validate()
    if (errorvalid) {
      return
    }
    //  调用创建团队的接口
    const res: any = await addTeamUsingPost(createTeamForm.value)
    if (res.code == 0) {
      Message.success('创建成功')
      router.push('/team/info')
    } else {
      Message.error(res.message || '创建失败')
    }
  } catch (e) {
    console.error(e)
  } finally {
    createTeamForm.value = {
      name: '',
      description: '',
      maxMember: 5
    }
  }
}

// 加载邀请记录
const teamUserHistoryPageRequest: Ref<API.listTeamUserHistoryUsingPOSTParams> = ref({
  pageNum: 1,
  pageSize: 1000,
  invitedId: userStore.user.id,
  applicantId: userStore.user.id,
  status: 1
})
const loadInviteRecords = async () => {
  try {
    // TODO: 调用获取邀请记录的接口
    const res: any = await listTeamUserHistoryUsingPost(teamUserHistoryPageRequest.value)
    inviteRecords.value = res.data.records
    console.log(inviteRecords.value)
  } catch (error) {
    Message.error('加载邀请记录失败')
    console.error(error)
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await loadInviteRecords()
})
</script>

<template>
  <div class="join-team">
    <div class="page-header">
      <h2>加入团队</h2>
      <p class="description">创建自己的团队，或加入其他团队</p>
    </div>

    <div class="content-container">
      <!-- 左侧：邀请记录 -->
      <div class="left-section">
        <Card class="invite-card">
          <template #title>
            <Space justify="space-between" align="center">
              <span>待处理的邀请</span>
              <Button type="primary" @click="createTeamVisible = true"> 创建团队 </Button>
              <span class="tip" style="font-size: 12px; color: var(--color-text-3)"
                >（目前仅支持创建一个团队）</span
              >
            </Space>
          </template>
          <div class="invite-list-wrapper">
            <List :data="inviteRecords" :bordered="false" class="invite-list">
              <template #empty>
                <Empty description="暂无待处理的邀请" />
              </template>
              <template #item="{ item }">
                <List.Item>
                  <div class="invite-item">
                    <div class="invite-info">
                      <div class="team-name">{{ item.teamName }}</div>
                      <div class="invite-detail">
                        <span>由</span>
                        <span class="highlight">{{ item?.inviter.name }}</span>
                        <span>邀请加入</span>
                        <span class="highlight">{{ item.teamName }}</span>
                        <span class="invite-time">{{
                          dayjs(item.createAt).format('YYYY-MM-DD HH:mm')
                        }}</span>
                      </div>
                    </div>
                    <div class="invite-actions">
                      <Space>
                        <Button
                          type="primary"
                          status="success"
                          size="small"
                          @click="handleInvite(item, true)"
                        >
                          接受
                        </Button>
                        <Button
                          type="primary"
                          status="danger"
                          size="small"
                          @click="handleInvite(item, false)"
                        >
                          拒绝
                        </Button>
                      </Space>
                    </div>
                  </div>
                </List.Item>
              </template>
            </List>
          </div>
        </Card>
      </div>

      <!-- 右侧：邀请链接 -->
      <div class="right-section">
        <Card class="invite-code-card">
          <template #title>使用邀请链接</template>
          <div class="invite-code-content">
            <!-- 邀请链接输入 -->
            <div class="input-group">
              <div class="input-label">邀请链接：</div>
              <div class="input-box">
                <Input
                  v-model="inviteLink"
                  placeholder="请输入邀请链接"
                  allow-clear
                  :disabled="isLinkDisabled"
                  @input="handleLinkInput"
                  :style="{ width: '100%' }"
                >
                  <template #prefix>
                    <icon-link />
                  </template>
                </Input>
              </div>
            </div>

            <!-- 邀请码输入 -->
            <div class="input-group">
              <div class="input-label">邀请码：</div>
              <div class="input-box">
                <Input
                  v-model="inviteCode"
                  placeholder="请输入邀请码"
                  allow-clear
                  :disabled="isCodeDisabled"
                  @input="handleCodeInput"
                  :style="{ width: '100%' }"
                >
                  <template #prefix>
                    <icon-code />
                  </template>
                </Input>
              </div>
            </div>

            <!-- 加入按钮 -->
            <div class="join-button-group">
              <Button
                type="primary"
                long
                :disabled="!inviteLink && !inviteCode"
                @click="handleJoinTeam"
              >
                加入团队
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </div>

    <!-- 创建团队弹窗 -->
    <Modal
      v-model:visible="createTeamVisible"
      title="创建团队"
      @cancel="createTeamVisible = false"
      :width="500"
    >
      <Form
        ref="formRef"
        :model="createTeamForm"
        :rules="rules"
        @submit="() => handleCreateTeam(createTeamForm, null)"
      >
        <FormItem field="name" label="团队名称" required>
          <Input v-model="createTeamForm.name" placeholder="请输入团队名称" allow-clear />
        </FormItem>

        <FormItem field="description" label="团队简介">
          <Textarea
            v-model="createTeamForm.description"
            placeholder="请输入团队简介"
            :max-length="300"
            show-word-limit
            allow-clear
          />
        </FormItem>

        <FormItem field="maxMember" label="人数上限" required>
          <Select
            v-model="createTeamForm.maxMember"
            :options="memberLimitOptions"
            placeholder="请选择团队人数上限"
          />
        </FormItem>
      </Form>
      <template #footer>
        <Space>
          <Button @click="createTeamVisible = false">取消</Button>
          <Button type="primary" @click="handleCreateTeam()">创建</Button>
        </Space>
      </template>
    </Modal>

    <!-- 添加错误提示 -->
    <div class="link-error-tip" v-if="inviteLink && !inviteLinkValid">请输入有效的邀请链接</div>
  </div>
</template>

<style scoped>
.join-team {
  padding: 20px;
  height: 100%;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  line-height: 32px;
}

.description {
  margin: 8px 0 0;
  color: var(--color-text-3);
  font-size: 14px;
  line-height: 22px;
}

.content-container {
  display: flex;
  gap: 20px;
  height: calc(100% - 80px);
}

.left-section {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 280px); /* 调整为视窗高度减去头部和边距 */
}

.invite-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.invite-list-wrapper {
  overflow-y: auto;
}

/* 确保卡片内容区域可以滚动 */
:deep(.arco-card-body) {
  flex: 1;
  overflow: hidden;
  padding: 0 20px;
  display: flex;
  flex-direction: column;
}

.right-section {
  width: 320px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.create-team-card,
.invite-code-card {
  width: 100%;
}

.create-team-card {
  flex-shrink: 0;
}

.invite-code-card {
  flex: 1;
  min-height: 0;
}

.create-team-content {
  padding: 8px 0;
}

.invite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.invite-info {
  flex: 1;
  min-width: 0;
}

.team-name {
  font-weight: 500;
  color: var(--color-text-1);
  margin-bottom: 4px;
}

.invite-detail {
  color: var(--color-text-3);
  font-size: 13px;
}

/* 添加以下样式 */
.invite-detail .highlight {
  color: var(--color-text-1);
  font-weight: 500;
  margin: 0 4px;
}

.invite-time {
  margin-left: 12px;
  color: var(--color-text-4);
}

.invite-actions {
  flex-shrink: 0;
  margin-left: 16px;
}

.invite-code-content {
  height: 100%;
}

.tip-section {
  margin-bottom: 24px;
}

.tip-section h3 {
  margin: 0 0 16px;
  font-size: 16px;
  color: var(--color-text-1);
}

.tip-section p {
  margin: 8px 0;
  color: var(--color-text-2);
  font-size: 14px;
}

.input-section {
  margin-top: 24px;
}

.input-section .tip {
  margin: 0 0 12px;
  color: var(--color-text-2);
}

/* 调整列表容器样式 */
.invite-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 4px;
}

/* 确保列表组件本身也是 flex 布局 */
:deep(.arco-list) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 确保列表内容区域可以滚动 */
:deep(.arco-list-content) {
  flex: 1;
  overflow-y: auto;
}

/* 调整列表项样式 */
:deep(.arco-list-item) {
  padding: 12px 0;
}

.radio-desc {
  margin-left: 8px;
  font-size: 12px;
  color: var(--color-text-3);
}

:deep(.arco-form-item-wrapper) {
  width: 100%;
}

:deep(.arco-checkbox) {
  width: 100%;
}

:deep(.arco-radio-group) {
  width: 100%;
}

.invite-link-input {
  display: flex;
  gap: 12px;
  margin: 20px 0;
}

.link-error-tip {
  color: var(--color-danger-light-4);
  font-size: 12px;
  margin-top: -16px;
  margin-bottom: 16px;
}

/* 添加相关样式 */
.input-group {
  margin-bottom: 20px;
}

.input-label {
  font-size: 14px;
  color: var(--color-text-2);
  margin-bottom: 8px;
}

.input-box {
  width: 100%;
}

.join-button-group {
  margin-top: 32px;
  padding: 0 20px;
}

:deep(.arco-input-wrapper) {
  background-color: var(--color-fill-2);
}

:deep(.arco-input-prefix) {
  color: var(--color-text-3);
}

/* 添加禁用状态样式 */
:deep(.arco-input-disabled) {
  cursor: not-allowed;
  background-color: var(--color-fill-2);
  color: var(--color-text-3);
}
</style>
